<template>
  <div class="info-wrap">
    <el-card
      v-if="!editing"
      class="box-card"
      :class="{invisibleCard: infoCard.enabled != 1}">
      <div slot="header" class="clearfix" style="line-height: 35px;">
        <span class="infoCard-title">{{infoCard.title}}</span>
        <div class="pull-right">
          <el-button type="text" class="danger" @click="handleremoveInfoCard">删除</el-button>
          <el-button type="text" @click="hidden">{{infoCard.enabled == 1 ? '隐藏' : '显示'}}</el-button>
          <el-button type="text" @click="editInfo">编辑</el-button>
        </div>
      </div>
      <div>
        <span class="infoCard-content">
          <pre>{{infoCard.content}}</pre>
        </span>
        <div
        class="pictures-display">
          <a
            v-for="(img, index) in allImg"
            :key="index"
            href="#"
            @click.prevent.stop="handlePictureCardPreview(img.url)">
            <img :src="img.url">
            <span class="img-mask">点击预览</span>
          </a>
        </div>
      </div>
    </el-card>
    <el-card
      class="box-card" v-else>
      <el-form
        :model="infoCard"
        ref="ruleForm"
        :rules="rules">
        <el-form-item prop="title">
          <el-input
            placeholder="请输入标题"
            v-model="infoCard.title">
          </el-input>
        </el-form-item>
        <el-form-item prop="content">
          <el-input
            type="textarea"
            :rows="7"
            placeholder="请输入内容"
            v-model="infoCard.content">
          </el-input>
        </el-form-item>
        <el-form-item>
          <div class="upload-wrap">
              <div
                class="pictures-display">
                <a v-for="(img, index) in allImg"
                  :key="index" href="#" @click.prevent.stop="handlePictureCardPreview(img.url)">
                  <img :src="img.url">
                  <span class="img-mask">点击预览</span>
                  <i class="el-icon-circle-cross" @click.stop.prevent.self="removeImg(img.name)"></i>
                </a>
                <div class="img-wrap">
                  <span class="upload-bg"></span>
                  <label for="" class="upload-img">
                    <i class="el-icon-plus"></i>
                    上传图片
                    <input type="file" accept="image/*" @change="uploadImg">
                  </label>
                </div>
              </div>
          </div>
        </el-form-item>
        <el-button type="primary" @click="submitForm" :loading="saveLoading">保存</el-button>
        <el-button @click="cancelEdit()">取消</el-button>
      </el-form>
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :modal-append-to-body="false">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
const md5 = require('md5');
import libs from 'libs/';
import { cloneDeep, merge } from 'lodash';
const imageUtil = libs.image


export default {
  props: {
    infoData: Object,
    itemIndex: Number,
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      infoCard: this.infoData,
      editing: !this.infoData.id,
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'change'},
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'change'},
        ]
      },
      imglist: cloneDeep(this.infoData.imglist),
      tempImages: [],
      tempImageUrls: [],
      saveLoading: false,
    };
  },
  computed: {
    allImg () {
      return [
        ...this.imglist,
        ...this.tempImages
      ]
    }
  },
  methods: {
    editInfo() {
      this.$emit('cancelOtherOperate');
      this.$emit('canOperate', () => {
        this.editing = true;
        this.imglist = cloneDeep(this.infoCard.imglist);
        this.tempImages = [];
        this.tempImageUrls = [];
      })
    },
    submitForm(callback) {
      this.saveLoading = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let successMessage;
          this.sendImg()
          .then(() => {
            const data = {...this.infoCard, imglist: JSON.stringify([...this.imglist, ...this.tempImageUrls])};
            if (this.infoCard.id) {
              successMessage = '更新成功';
              // return updateInfoCard(data);
              // console.log('update data', data);
              // this.$$api_researchTools_updateInfoCard({
              //   restfulReq: {
              //     id: data.id
              //   },
              //   data: {
              //     name: 'cc',
              //   },

              //   succFn: res => {
              //     console.log(res);
              //   }
              // })
              this.$$api_researchTools_updateInfoCard({
                restfulReq: {id: data.id},
                data: data,
                succFn: (res) => {
                  console.log('修改成功', res);
                  this.updateData(res, successMessage, callback);
                }
              })
            } else {
              successMessage = '创建成功';
              // return createInfoCard(data);
              this.$$api_researchTools_createInfoCard({
                restfulReq: data,
                succFn: (res) => {
                  console.log('创建成功', res);
                  this.updateData(res, successMessage, callback);
                }
              })
            }
          })
          // }).then((res) => {
          //   this.infoCard = merge(this.infoCard, res.data);
          //   // 图片不merge
          //   this.infoCard.imglist = res.data.imglist;
          //   this.$message.success(successMessage);
          //   this.editing = false;
          //   this.saveLoading = false;
          //   callback && callback();
          // }).catch(err => {
          //   this.$message.error(err);
          //   this.saveLoading = false;
          // })
        } else {
          this.$message({
            message: '内容未填写完整',
            type: 'warning'
          });
          this.saveLoading = false;
        }
      })
    },
    updateData(res, successMessage, callback) {
      this.infoCard = merge(this.infoCard, res);
      // 图片不merge
      this.infoCard.imglist = res.imglist;
      this.$message.success(successMessage);
      this.editing = false;
      this.saveLoading = false;
      console.log('执行', saveLoading);
      callback && callback();
    },
    cancelEdit(callback) {
      if (this.infoCard.id == 0) {
        this.$emit('remove', this.infoCard);
      } else {
        this.$refs.ruleForm.resetFields();
        this.tempImages = [];
        this.tempImageUrls = [];
        this.imglist = cloneDeep(this.infoCard.imglist);
      }
      this.editing = false;
      callback && callback();
    },
    handleremoveInfoCard() {
      this.$emit('cancelOtherOperate');
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // removeInfoCard({id: this.infoCard.id})
        // .then(res => {
        //   this.$emit('remove', this.infoCard);
        //   this.$message({
        //     type: 'success',
        //     message: '删除成功!'
        //   });
        // }).catch(err => {
        //   this.$message.error(err);
        // });
        this.$$api_researchTools_removeInfoCard({
          restfulReq: {id: this.infoCard.id},
          succFn: (res) => {
            console.log('删除成功', res);
            this.$emit('remove', this.infoCard);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
        })
      }).catch(() => {
      });
    },
    // 隐藏信息卡片
    hidden() {
      this.$emit('cancelOtherOperate');
      const enabled = this.infoCard.enabled == 1 ? 0 : 1;
      // enableInfoCard({id: this.infoCard.id, enabled})
      // .then(res => {
      //   this.infoCard.enabled = enabled;
      //   if (enabled == 1) {
      //     this.$message.success('已显示');
      //   } else {
      //     this.$message.success('已隐藏');
      //   }
      // }).catch(err => {
      //   this.$message.error(err.message)
      // })

      this.$$api_researchTools_updateInfoCard({
        restfulReq: {id: this.infoCard.id, enabled},
        succFn: (res) => {
          console.log('显示/隐藏成功', res);
          this.infoCard.enabled = enabled;
          if (enabled == 1) {
            this.$message.success('已显示');
          } else {
            this.$message.success('已隐藏');
          }
        }
      })
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    uploadImg(event) {
      var fr = new FileReader();
      fr.onload = (e) => {
        let id = Date.now();
        // 当fr加载时，把图片的内容赋值给
        this.tempImages.push({url: e.target.result, name: Date.now(), type: event.target.files[0].type});
        event.target.value = '';
      };
      // 读取选中的图片，并转换成dataURL格式
      fr.readAsDataURL(event.target.files[0]);
      // 清空
    },
    sendImg() {
      return new Promise((resolve, reject) => {
        if (this.tempImages.length <= 0) {
          resolve(true);
        }
        let allPromise = [];
        for (let i = 0; i < this.tempImages.length; i++) {
          const name = md5(`${this.infoCard.colg_id}infocard${Date.now()}`);
          const key = `acagrid/universitycontent/tianhe/images/${name}`;
          const imgUrl = `https://img.okay.do/acagrid/universitycontent/tianhe/images/${name}`;
          // console.log('util', imageUtil);
          const blob = imageUtil.base64ToBlob(this.tempImages[i].url);
          allPromise.push(new Promise((resolve, reject) => {


            imageUtil.uploadImg(blob, key, () => {

              this.tempImageUrls.push({
                name: key,
                type: this.tempImages[i].type,
              });
              resolve(true);
            })
          }))
        }
        Promise.all(allPromise).then(function(values) {
          resolve(true);
        });
      })
    },
    removeImg(name) {
      this.imglist = this.imglist.filter(item => item.name != name);
      this.tempImages = this.tempImages.filter(item => item.name != name);
    }
  }
}
</script>

<style scoped lang="scss">
.infoCard-title {
  font-size: 18px;
  color: #1F2D3D;
}
.info-wrap {
  margin-bottom: 20px;
}
.danger {
  color: #FF4949;
  &:hover {
    color: #f78989;
  }
}
.pictures-display {
  img {
    width: 50px;
    height: 50px;
    border-radius: 4px;
  }
  a {
    position: relative;
    display: inline-block;
    height: 50px;
    margin-top: 14px;
    margin-right: 16px;
    span {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #000000;
      opacity: .3;
      color: #fff;
      font-size: 12px;
      line-height: 50px;
      border-radius: 4px;
    }
    i {
      display: none;
      position: absolute;
      top: -15px;
      right: -15px;
      font-size: 20px;
      color: #666;
      z-index: 2;
      padding: 5px;
    }
    &:hover {
      span,
      i {
        display: inline-block;
      }
    }
  }
}
.infoCard-content {
  pre {
    margin-top: 0;
    line-height: 28px;
    white-space: pre-wrap;
    word-break: break-all;
    color: #5E6D82;
    margin-bottom: 0;
  }
}
.invisibleCard {
  border: 1px dashed #C0CCDA;
  .infoCard-title {
    color: #8d949d;
  }
  .infoCard-content,
  pre {
    color: #C0CCDA;
  }
}
.img-wrap {
  height: 50px;
  display: inline-block;
  position: relative;
  overflow: hidden;
  border: 1px solid #C0CCDA;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 14px;
  .upload-bg {
    display: inline-block;
    height: 50px;
    width: 50px;
    background: #F9FAFC;
  }
  .upload-img {
    position: absolute;
    left: 0;
    top: 4px;
    width: 100%;
    text-align: center;
    font-size: 11px;
    line-height: 25px;
    color: #A7B5C8;
    i {
      display: block;
      font-size: 20px;
    }
    input {
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0;
      cursor: pointer;
      width: 100%;
      height: 100%;
    }
  }
}
</style>
<style lang="scss">
.box-card {
  .el-card__header {
    padding: 7px 2px;
    margin: 0 20px;
  }
}
</style>

